package com.shushan.exam;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.async.NetStringListener;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.BaseActivity;
import com.shushan.base.BaseFragment;
import com.shushan.base.Constants;
import com.shushan.exam.adapter.AnswerAdapter;
import com.shushan.exam.adapter.ReportSelectorsAdapter;
import com.shushan.exam.adapter.VideoPointsAdapter;
import com.shushan.exam.bean.ExerciseBean;
import com.shushan.exam.bean.ExerciseOptionBean;
import com.shushan.exam.bean.ExerciseVideoBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.shushanbao.R;
import com.shushan.util.DialogUtil;
import com.shushan.util.ImageUtils;

import java.util.List;

import android.content.DialogInterface;
import android.widget.FrameLayout;

import com.shushan.ui.CustomDialog;
import com.shushan.util.ToolUtils;

/**
 * @ClassName: ExamFragment
 * @Desciption: 考试每页的fragment
 * @author: yichaohua
 * @date: 2018-01-05
 */
public class ExamFragment extends BaseFragment implements AdapterView.OnItemClickListener, View.OnClickListener {

    private static final String TAG = "ExamFragment";

    private View view;
    private ListView answerListView;
    private ListView videoPointsListView;
    private LinearLayout pointsLayout;
    private AnswerAdapter answerAdapter;
    private TextView questionText;
    private ImageView questionImg;
    private ImageView ivIdontKnow;
    private FrameLayout flVideoTitleBar;
    private TextView tvVideoTitleBar;
    private Button btnQuestionReport;
    private TextView tvRightSelector;
    private LinearLayout llOtherReason;
    private EditText etOtherReason;
    private Button btnReport;

    private boolean hasClickIdontKnow = false;
    private boolean isOnlyDisplay = false;
    private ExerciseBean exerciseBean;
    private int examIndex;
    private OnAnswerSelectListener onAnswerSelectListener;

    private CustomDialog skipTopicDialog;
    private Dialog reportDialog;
    private String reportStr;

    public static ExamFragment newInstance(boolean isOnlyDisplay, int examIndex, ExerciseBean exerciseBean) {

        ExamFragment examFragment = new ExamFragment();
        examFragment.setOnlyDisplay(isOnlyDisplay);
        examFragment.setExamIndex(examIndex);
        examFragment.setExerciseBean(exerciseBean);

        return examFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.exam_fragment, null);

            initView(view);

            initData();
        }

        return view;
    }

    private void initView(View view) {
        pointsLayout = view.findViewById(R.id.exam_fragment_video_layout);
        answerListView = view.findViewById(R.id.exam_fragment_answer_lv);
        answerListView.setOnItemClickListener(this);
        videoPointsListView = view.findViewById(R.id.exam_fragment_video_lv);
        questionText = view.findViewById(R.id.exam_fragment_question_tv);
        questionImg = view.findViewById(R.id.exam_fragment_question_img);
        ivIdontKnow = view.findViewById(R.id.iv_idont_know);
        ivIdontKnow.setOnClickListener(this);
        flVideoTitleBar = view.findViewById(R.id.fl_video_title_bar);
        tvVideoTitleBar = view.findViewById(R.id.tv_video_title_bar);
        btnQuestionReport = view.findViewById(R.id.btn_question_report);
        btnQuestionReport.setOnClickListener(this);
        tvRightSelector = view.findViewById(R.id.tv_right_selector);
        if(!Constants.isForEditors){
            tvRightSelector.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_idont_know:
                if (ExamActivity.isSkipTopic()) {
                    showSkipTopicDialog(ExamActivity.getShouldAnswerIndex());
                    return;
                }
                hasClickIdontKnow = true;

                flVideoTitleBar.setBackground(getResources().getDrawable(R.drawable.orange_rect_top_right_shape));
                tvVideoTitleBar.setText("先学学，再做题");
                showTopicVideos(true);
                break;
            case R.id.btn_question_report://问题反馈
                reportDialog.show();
                break;
            case R.id.btn_report://其他原因的确定按钮
                String reason = etOtherReason.getText().toString();
                if(TextUtils.isEmpty(reason)){
                    showToast("反馈信息不能为空");
                    return;
                }
                Log.i(TAG,"onclick() : reason == "+reason);
                reportReason(reason);
                reportDialog.dismiss();
                break;
        }
    }

    private void reportReason(String reason) {
        UrlParse urlParse = new UrlCommParse(getContext(), UrlConst.BASE_URL).appendRegion(UrlConst.QUESTION_REPORT);
        UrlParse paramParse = new UrlCommParse(getContext())
                .putValue("result", reason)
                .putValue("exercises_id", exerciseBean.id);
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStringListener() {
                    @Override
                    protected void onSuccess(String data) {
                        DialogUtil.showHintDialog(getActivity(), R.drawable.ic_success, "反馈提交成功，我们将\n尽快处理！");
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void showSkipTopicDialog(final int shouldAnswerIndex) {
        skipTopicDialog = new CustomDialog.Builder(getContext())
                .setTitle("温馨提示")
                .setMessage("第" + (shouldAnswerIndex + 1) + "题还没有作答")
                .setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("返回第" + (shouldAnswerIndex + 1) + "题", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        Intent intent = new Intent(Constants.JUMP_TO_SHOULD_ANSWER_TOPIC_ACTION);
                        intent.putExtra("shouldAnswerIndex", shouldAnswerIndex);
                        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
                    }
                })
                .create();
        skipTopicDialog.show();
    }

    private void showTopicVideos(boolean hideIdontKnow) {
        if (exerciseBean == null) {
            Log.e(TAG, "exerciseBean == null");
            return;
        }

        List<ExerciseVideoBean> videoPointList = exerciseBean.getVideoList();
        if (videoPointList != null && videoPointList.size() > 0) {
            pointsLayout.setVisibility(View.VISIBLE);

            videoPointsListView.setAdapter(new VideoPointsAdapter((BaseActivity) getActivity(), videoPointList));
        } else {
            pointsLayout.setVisibility(View.GONE);

        }
        if (hideIdontKnow) {
            ivIdontKnow.setVisibility(View.GONE);
        }
    }

    private void initData() {
        if (exerciseBean == null) {
            Log.e(TAG, "exerciseBean == null");
            return;
        }
        //@{显示正确选项，审题用@{
        if(Constants.isForEditors) {
            List<ExerciseOptionBean> exerciseOptionBeanList = exerciseBean.getOptionList();
            String[] selectors = getContext().getResources().getStringArray(R.array.exam_answer_label_array);
            for (int i = 0; i < exerciseOptionBeanList.size(); i++) {
                if (exerciseOptionBeanList.get(i).option_result == 1) {
                    tvRightSelector.setText(selectors[i]);
                }
            }
        }
        //@}
        if (exerciseBean.content_type.equals("TEXT")) {
            questionText.setVisibility(View.VISIBLE);
            questionImg.setVisibility(View.GONE);

            questionText.setText(exerciseBean.exercises_content);
        } else {
            questionText.setVisibility(View.GONE);
            questionImg.setVisibility(View.VISIBLE);

            ImageUtils.loadImageNoBg(getActivity(), exerciseBean.exercises_imgs, questionImg);
        }

        answerAdapter = new AnswerAdapter(getActivity(), exerciseBean);
        answerAdapter.setOnlyDisplay(isOnlyDisplay);
        answerListView.setAdapter(answerAdapter);

        boolean isNoVideo = false;
        List<ExerciseVideoBean> videoPointList = exerciseBean.getVideoList();
        if (!(videoPointList != null && videoPointList.size() > 0)) {
            isNoVideo = true;
        }
        if (isOnlyDisplay) {
            btnQuestionReport.setVisibility(View.VISIBLE);
            ivIdontKnow.setVisibility(View.GONE);
            if (videoPointList != null && videoPointList.size() > 0) {
                pointsLayout.setVisibility(View.VISIBLE);

                videoPointsListView.setAdapter(new VideoPointsAdapter((BaseActivity) getActivity(), videoPointList));
            } else {
                pointsLayout.setVisibility(View.GONE);

            }
        } else {
            if (!(videoPointList != null && videoPointList.size() > 0)) {
                ivIdontKnow.setVisibility(View.GONE);
            }
        }
        initReportDialog(isNoVideo);
    }

    private void initReportDialog(boolean isNoVideo) {
        reportDialog = new Dialog(getContext(), R.style.Dialog_Translucent_Background);
        reportDialog.setContentView(R.layout.dialog_question_report);
        llOtherReason = reportDialog.findViewById(R.id.ll_other_reason);
        etOtherReason = reportDialog.findViewById(R.id.et_other_reason);
        etOtherReason.setInputType(InputType.TYPE_TEXT_FLAG_MULTI_LINE);
        //文本显示的位置在EditText的最上方
        etOtherReason.setGravity(Gravity.TOP);
        //改变默认的单行模式
        etOtherReason.setSingleLine(false);
        //水平滚动设置为False
        etOtherReason.setHorizontallyScrolling(false);
        btnReport = reportDialog.findViewById(R.id.btn_report);
        btnReport.setOnClickListener(this);
        RecyclerView rvQuestionSelectors = reportDialog.findViewById(R.id.rv_question_selectors);
        rvQuestionSelectors.setLayoutManager(new LinearLayoutManager(getContext()));
//        rvQuestionSelectors.addItemDecoration(new RecyclerViewDivider());
        ReportSelectorsAdapter adapter = new ReportSelectorsAdapter(getContext(), isNoVideo);
        adapter.setOnItemClickListener(new ReportSelectorsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position, boolean isNoVideo) {
                String[] reportSelector = ExamFragment.this.getContext().getResources().getStringArray(R.array.question_report_selectors_text_array);
                int resultId = position;
                boolean isOther = false;
                Log.i(TAG, "resultId == " + resultId);
                if (isNoVideo && resultId > 2) {
                    resultId++;
                }
                if (resultId == 5) {
                    llOtherReason.setVisibility(View.VISIBLE);
                    isOther = true;
                } else {
                    reportStr = reportSelector[resultId];
                }
                Log.i(TAG, "finally resultId == " + resultId+" ; reason == "+reportStr+" ; isOther == "+isOther);
                btnQuestionReport.setVisibility(View.GONE);
                if (!isOther) {
                    reportDialog.dismiss();
                    reportReason(reportStr);
                }
            }
        });
        rvQuestionSelectors.setAdapter(adapter);
        reportDialog.getWindow().setWindowAnimations(R.style.DialogEnterOutAnim);
        reportDialog.setCanceledOnTouchOutside(true);
    }

    public ExerciseBean getExerciseBean() {
        return exerciseBean;
    }

    public void setExerciseBean(ExerciseBean exerciseBean) {
        this.exerciseBean = exerciseBean;
    }

    public int getExamIndex() {
        return examIndex;
    }

    public void setExamIndex(int examIndex) {
        this.examIndex = examIndex;
    }

    public boolean isOnlyDisplay() {
        return isOnlyDisplay;
    }

    public void setOnlyDisplay(boolean onlyDisplay) {
        isOnlyDisplay = onlyDisplay;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (isOnlyDisplay) {
            return;
        }

        List<ExerciseOptionBean> exerciseOptionList = answerAdapter.getExerciseOptionList();
        ExerciseOptionBean exerciseOptionBean = exerciseOptionList.get(position);

        if (exerciseOptionBean.getAnswerIndex() < 0) {

            if (onAnswerSelectListener != null) {
                if (!onAnswerSelectListener.onAnswerSelect(examIndex, exerciseOptionBean.option_result == 1 ? true : false)) {
                    Log.d(TAG, "onAnswerSelectListener return false");
                    return;
                }
                exerciseOptionBean.setAnswerIndex(position);
                answerAdapter.notifyDataSetChanged();
                sendAnsweredBroadcast();

                answerListView.setOnItemClickListener(null);

                if (!hasClickIdontKnow) {
                    showTopicVideos(true);
                }
                btnQuestionReport.setVisibility(View.VISIBLE);
            }
        }
    }

    private void sendAnsweredBroadcast() {
        Intent intent = new Intent();
        intent.setAction(Constants.ANSWERED_RECEIVER_ACTION);
        LocalBroadcastManager.getInstance(getContext()).sendBroadcast(intent);
    }

    public OnAnswerSelectListener getOnAnswerSelectListener() {
        return onAnswerSelectListener;
    }

    public void setOnAnswerSelectListener(OnAnswerSelectListener onAnswerSelectListener) {
        this.onAnswerSelectListener = onAnswerSelectListener;
    }

    private class RecyclerViewDivider extends RecyclerView.ItemDecoration {

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
            super.getItemOffsets(outRect, view, parent, state);
            outRect.set(0, 0, 0, ToolUtils.dip2px(getContext(), 18));
        }
    }

}